﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ivy.UserManagement.Entity;
using Ivy.UserManagement.BusinessLogic;

using Ivy.SiteAdministration.Entity;
using Ivy.SiteAdministration.BusinessLogic;

using Ivy.SiteAdministration.Entity;
using Ivy.SiteAdministration.BusinessLogic;

using FrameworkIvy.App_Code;


namespace FrameworkIvy.UserControls
{
    public partial class LoginControl : System.Web.UI.UserControl
    {
        #region  Variable & constant
        // All constants and local variable should be declared here
        // TRY NOT TO CREATE PUBLIC VARIABLES INSTEAD USE PROPERTIES FOR THAT PURPOSE.
        // Variable naming convention :- 
        // The naming should be self explanatory, make it long to explain the purpose 
        // and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // Naming convention for all local variable should start with underscore "_"
        // Naming convention for all local constant should start with "_The"
        // Example :    string _CustomerCode = string.Empty;
        // Example :    const string _TheDefaultSmtpServer = "DefaultSmtpServer";
        // ==================== START YOUR CODE FROM NEXT LINE ========================
        const string _TheDefaultUserContextSessionVariableName = "UserContext";

        #endregion  Variable & constant

        #region Constructor & Destructor
        // Generally not needed in UI layer.
        // Cut and Copy the default constructor for the class inside this region.
        // Generally not required in UI layer.
        // Example:
        // public SampleClassTemplate()
        // {

        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================


        #endregion Constructor & Destructor

        #region Properties
        // Any value/variable that needs to be exposed outside the class we need to create a property.
        // Avoid creating public variables rather create public properties.
        // UI layer may have public custom properties. these are very handy for User Controls.
        // Property naming convention :- Properties will be exposed outside the class, 
        // the naming should be self explanatory, make it long to explain the purpose 
        // and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // All properties should have a corresponding local variable 
        // and the property name and local variable name should match.
        // Example :
        // public string CustomerCode
        // {
        //     get
        //     {
        //         return _CustomerCode;
        //     }
        //     set
        //     {
        //         _CustomerCode = value;
        //     }
        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================


        #endregion Properties

        #region Events
        // Generally UI layer will have public events.
        // Cut and Copy the default generated events for the class inside this region.
        // ==================== START YOUR CODE FROM NEXT LINE ========================

        protected void Page_Load(object sender, EventArgs e)
        {
            try //All events in pages or user control should have try{} catch {} block.
            {
                //First check if the current logged in user is having proper role/authorization to access this page or not.
                if (IsUserAutherization())
                {
                    //TODO - Your code to display the initial layout/data etc.

                }
                else
                {
                    //TODO - Your code to redirect page to "NOT AUTHORIZED" page or any other page as required by the business logic.
                }
            }
            catch (Exception ex)
            {
                //ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            UserManagementBus lUserManagementBus = new UserManagementBus();
            if (lUserManagementBus.Login(this.txtUserID.Text, this.txtPassword.Text))
            {
                User lUser = lUserManagementBus.GetUserByLoginID(this.txtUserID.Text);
                //Update SessionLog
                UpdateSessionLogWithLoginUserDetails(lUser.UserPersonKey);
                //Initialize screen for next step.
                List<UserOrganizationRole> lUserOrganizationRoles = lUserManagementBus.GetUserOrganizationRolesForSelectedUser(lUser.UserPersonKey);
                InitializeAuthenticatedUserAsCurrentLoginUser(lUser, lUserOrganizationRoles);
                LoginStepCompletionMessageDisplay();
            }
            else
            {
                this.LoginFailure.InnerHtml = ("Login Failure - Usename and password are not matching");
            }
        }
        protected void btnPrimaryEmailIsYes_Click(object sender, EventArgs e)
        {
            User _User = SessionUtility.GetCurrentLoginUser();
            UserManagementBus lUserManagementBus = new UserManagementBus();
            Person _Person = lUserManagementBus.GetPersonByKey(_User.UserPersonKey);
            Response.Redirect("~/UserManagement/UserPrimaryEmailVerification.aspx?ScreenMode=3&PersonPrimaryEmail=" + _Person.PersonPrimaryEmailID);
            this.LoginSuccessMessageModalPopupExtender.Hide();
           
        }
        protected void btnPrimaryEmailIsNo_Click(object sender, EventArgs e)
        {
            this.LoginSuccessMessageModalPopupExtender.Hide();
            Response.Redirect("~/UserManagement/MyDashboard.aspx");
        }
        #endregion Events

        #region Public Methods
        // UI layer may have public custom Methods. These are very handy for User Controls.
        // Any method that needs to be exposed outside the class will be created inside this region.
        // Public Method naming convention :- Public Method will be exposed outside the class, 
        // The input and output parameters are also going to be exposed outside the class
        // the naming should be self explanatory, make it long to explain the purpose 
        // and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // Example :
        // public bool RegisterNewCustomer(Customer Customer)
        // {
        //     bool IsCustomerDataSaved = false;
        //     //TO DO logic to save data
        //     IsCustomerDataSaved = InsertCustomerDataUsingDao(Customer);
        //     return IsCustomerDataSaved;
        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================


        #endregion Public Methods

        #region Private Methods
        // All local class level methods will be inside this region. Mostly these are helper methods.
        // Private Method naming convention :- The naming should be self explanatory, 
        // make it long to explain the purpose and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // Input parameter will have a "p" as prefix. 
        // This will help the parameter variable that the value is originated outside this private method.
        // Example :
        // public bool InsertCustomerDataUsingDao(Customer pCustomer)
        // {
        //     bool IsCustomerDataInsertedSuccessfully = false;
        //     //TO DO logic to save data
        //     //....
        //     //....
        //     return IsCustomerDataInsertedSuccessfully;
        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================


        /// <summary>
        /// This method is to check if the current logged in user is having proper role/authorization to access this page or not.
        /// </summary>
        private bool IsUserAutherization()
        {
            bool _IsUserAutherization = false;
            //TODO - Your code to check authorization goes here.

            //for the time being let us allow the user to access this page.
            //but remove the below line once you have a proper logic.
            //==================== START YOUR CODE FROM NEXT LINE ========================

            //Currently allowing anyuser to use this page. However if any user is currently logged in will be forcefully logged out.
            //if (Session[_theDefaultUserContext] != null)
            //{
            //    UserContext tempUserSession = (UserContext)Session[_theDefaultUserContext];
            //    if (tempUserSession.CurrentUser != null)
            //    { 
            //        //Code to either display alert that "Current login user is will be logged out"

            //        tempUserSession.ResetCurrentUser();
            //        tempUserSession.ResetCurrentUserOrganizationRoles();

            //        //Putting back the tempUserSession changes to actual session variable.
            //        Session[_theDefaultUserContext] = tempUserSession;
            //    }
            //}
            _IsUserAutherization = true;

            return _IsUserAutherization;
        }

        /// <summary>
        /// This method is to clear all UI controls which are data binded.
        /// </summary>
        private void ClearScreen()
        {
        }

        /// <summary>
        /// This method is to bind all the UI control like dropdown list or list box etc with the required initial data, 
        /// </summary>
        private void FillLoadLookUpData()
        {
        }

        
        /// <summary>
        /// This method is to load the UI with initial set of data based of the business logic.
        /// </summary>
        private void InitializeScreen()
        {
            ClearScreen();
            FillLoadLookUpData();
        }
        private void InitializeAuthenticatedUserAsCurrentLoginUser(User pUser, List<UserOrganizationRole> pUserOrganizationRoles)
        {

            UserContext tempUserSession;
            if (Session[_TheDefaultUserContextSessionVariableName] != null)
            {
                tempUserSession = (UserContext)Session[_TheDefaultUserContextSessionVariableName];
            }
            else
            {
                //Generally this set should never get executed. 
                //As Session object should always be created once a new session gets started to update the sesion log
                tempUserSession = new UserContext();
            }

            tempUserSession.CurrentUser = pUser;
            tempUserSession.CurrentUserOrganizationRoles = pUserOrganizationRoles;
            Session[_TheDefaultUserContextSessionVariableName] = tempUserSession;
            //this.lblLoginSuccessful.Text = "Welcome " + tempUserSession.CurrentUser.UserLoginId.Trim();
        }

        private void InitializeSelectedUserOrganizationAsCurrentUserOrganization(Sys_OrganizationMaster pUserOrganizationSociety)
        {
            UserContext tempUserSession;
            if (Session[_TheDefaultUserContextSessionVariableName] != null)
            {
                tempUserSession = (UserContext)Session[_TheDefaultUserContextSessionVariableName];
            }
            else
            {
                //Generally this set should never get executed. 
                //As Session object should always be created once a new session gets started to update the sesion log
                tempUserSession = new UserContext();
            }
            tempUserSession.LoginOrganization = pUserOrganizationSociety;

            Session[_TheDefaultUserContextSessionVariableName] = tempUserSession;

        }


        private void InitializeSelectedUserRoleAsCurrentUserRole(Sys_RoleMaster pUserRole)
        {
            UserContext tempUserSession;
            if (Session[_TheDefaultUserContextSessionVariableName] != null)
            {
                tempUserSession = (UserContext)Session[_TheDefaultUserContextSessionVariableName];

            }
            else
            {
                //Generally this set should never get executed. 
                //As Session object should always be created once a new session gets started to update the sesion log
                tempUserSession = new UserContext();
            }
            tempUserSession.LoginRole = pUserRole;

            Session[_TheDefaultUserContextSessionVariableName] = tempUserSession;

        }

        /// <summary>
        /// This method is to copy the entity properties that need to be displayed in the UI controls to the UI control.
        /// Example - [pUser] is an instance of an entity and is filled with specific USER data.
        /// and this user instance is to be displayed is an UI control text boxes.
        /// A sample code will look like the following:
        ///  this.txtFirstName.Text = pUser.UserFirstName; 
        ///  this.txtLastName.Text  = pUser.UserLastName; 
        ///  this.txtLoginId.Text   = pUser.UserLoginID;
        /// </summary>
        private void TranslateEntityToUIControls()
        {

        }

        /// <summary>
        /// This method is to copy the user entered data from the UI controls to the entity instance that will be used to sent the entity to any other layer.
        /// Example - [pUser] is an instance of an entity and is to be filled with specific USER data that has been captured in the screen.
        /// A sample code will look like the following:
        ///  pUser.UserFirstName = this.txtFirstName.Text; 
        ///  pUser.UserLastName  = this.txtLastName.Text; 
        ///  pUser.UserLoginID   = this.txtLoginId.Text; 
        /// </summary>
        private void TranslateUIControlsToEntity()
        {


        }

        private void LoginStepCompletionMessageDisplay()
        {
            User lUser = SessionUtility.GetCurrentLoginUser();
            Sys_OrganizationMaster lSys_OrganizationMaster = SessionUtility.GetCurrentLoginUserOrzanization();
            Sys_RoleMaster lSys_RoleMaster = SessionUtility.GetCurrentLoginUserRole();
            string lUserWelcomeMessage = string.Empty;

            string lCurrentSocietyMessage = string.Empty;
            string lCurrentSocietyStepMessage = string.Empty;

            string lUserRoleMessage = string.Empty;
            string lUserRoleStepMessage = string.Empty;
            if (lUser != null)
            {
                lUserWelcomeMessage = "Welcome [" + lUser.UserLoginId + "]";
            }
            this.lblLoginSuccessfullMessage.InnerHtml = lUserWelcomeMessage;
            InitializeScreenForIsUserPrimaryEmailVerified();
        }

        private void InitializeScreenForIsUserPrimaryEmailVerified()
        {
            User lUser = SessionUtility.GetCurrentLoginUser();
            UserManagementBus lUserManagementBus = new UserManagementBus();
            Person _Person = lUserManagementBus.GetPersonByKey(lUser.UserPersonKey);
            if (_Person.PersonPrimaryEmailIsVerified == false)
            {
                this.lblPrimaryEmailVerified.InnerText = _Person.PersonPrimaryEmailID;
                this.DivPrimaryEmailVrification.Visible = true;
                this.LoginSuccessMessageModalPopupExtender.Show();
            }
            else
            {

                this.DivPrimaryEmailVrification.Visible = false;
                Response.Redirect("~/UserManagement/MyDashboard.aspx");
            }
        }
        private void UpdateSessionLogWithLoginUserDetails(int pUserPersonKey)
        {
            UserContext tempUserSession;
            if (Session[_TheDefaultUserContextSessionVariableName] != null)
            {
                tempUserSession = (UserContext)Session[_TheDefaultUserContextSessionVariableName];
                SiteAdministrationBus _SiteAdministrationBus = new SiteAdministrationBus();
                Sys_SessionLog _Sys_SessionLog = _SiteAdministrationBus.GetSys_SessionLogByUserSessionID(tempUserSession.UserSessionID);
                _Sys_SessionLog.UserKey = pUserPersonKey;
                _Sys_SessionLog.Sys_ModifiedByID = pUserPersonKey.ToString();
                _SiteAdministrationBus.UpdateUserSys_SessionLogDetails(_Sys_SessionLog);
            }
        }
        #endregion Private Methods
    }
}